package com.admin.sys.base.websocket.entity;

import javax.websocket.Session;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class SessionPool {
 
    public static Map<String, Session> sessionMap = new ConcurrentHashMap<>();
 
    public static void close(String sessionId){
        for (String userId : SessionPool.sessionMap.keySet()) {
            Session session = sessionMap.get(userId);
            if (session.getId().equals(sessionId)) {
                sessionMap.remove(userId);
                break;
            }
        }
    }
 
    public static void sendMessage(String sessionId, String message) {
        sessionMap.get(sessionId).getAsyncRemote().sendText(message);
    }
 
 
    public static void sendMessage(String message) {
        for (String sessionId : SessionPool.sessionMap.keySet()) {
            sessionMap.get(sessionId).getAsyncRemote().sendText(message);
        }
    }
 
 
    public static void sendMessage(Map<String, Object> params) {
        // 接收消息进行封装，以及写入数据库也在这边实现
        try {
            Session session = sessionMap.get(params.get("userId").toString());
            if (session != null) {
                session.getAsyncRemote().sendText(params.get("message").toString());
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}